<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "images".
 *
 * @property int $id
 * @property string $path 完整路径
 * @property string|null $base64 base64
 * @property string $thumbnail_path 缩略图路径
 * @property string $bucket
 * @property string $create_time
 * @property string $update_time
 */
class Images extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'images';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['base64'], 'string'],
            [['create_time', 'update_time'], 'safe'],
            [['path', 'thumbnail_path', 'bucket'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'path' => 'Path',
            'base64' => 'Base64',
            'thumbnail_path' => 'Thumbnail Path',
            'bucket' => 'Bucket',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    /**
     * Save timestamp
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;

                // 保存base64到数据表 (只保存小于5k的)
                // $base64 = $this->generateBase64($this->path);
                // $len = strlen($base64);
                // if ($len / 1024 < 5) {
                //     $this->base64 = $base64;
                // }
            }
            return true;
        }
        return false;
    }

    /**
     * delete image path
     *
     * @return bool
     */
    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        // delete image path
        $path = Yii::$app->getBasePath() . '/web' . $this->path;
        @unlink($path);

        return true;
    }

    public function generateBase64($path)
    {
        $path = Yii::$app->getBasePath() . '/web' . $path;

        return self::image2base64($path);
    }

    /**
     * image to base64
     * @param $path
     * @return string
     */
    public static function image2base64($path)
    {
        if ($fp = fopen($path, 'rb', 0)) {
            $gambar = fread($fp, filesize($path));
            fclose($fp);

            $base64 = chunk_split(base64_encode($gambar));
            // $encode = '<img src="data:image/jpg/png/gif;base64,' . $base64 .'" >';
            $encode = sprintf('data:image/jpg/png/gif;base64,%s', $base64);

            return $encode;
        }
    }

    /**
     * base64 to image
     *
     * @param $base64
     * @param $path
     */
    public static function base642image($base64, $path)
    {
        file_put_contents($path, base64_decode($base64));
    }

    public static function clearImages()
    {
        // todo
        // uploads dir
        // exist table
        // (path or thumbnail_path) and bucket
    }
}
